package com.daxidi.cn.utils;

import com.daxidi.cn.config.SystemPropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Random;

@Configuration
public class GenerateHtmlUtils {

    private static SystemPropertiesConfig systemPropertiesConfig;

    private static String range = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Autowired
    public void init(SystemPropertiesConfig systemPropertiesConfig) {
        GenerateHtmlUtils.systemPropertiesConfig = systemPropertiesConfig;
    }

    /**
     * 随机生成7位字符串
     *
     * @return
     */
    public static synchronized String getRandomString() {
        Random random = new Random();
        StringBuffer result = new StringBuffer();
        //要生成几位，就把这里的数字改成几
        for (int i = 0; i < 7; i++) {
            result.append(range.charAt(random.nextInt(range.length())));
        }
        return result.toString();
    }

    public static String genHtml(String htmlContent) throws UnsupportedEncodingException {
        String fileUrl = "";
        String htmlName = "";
        fileUrl = getRandomString() + String.valueOf(System.currentTimeMillis()).substring(6);
        htmlName = fileUrl + ".html";
        String fileName = systemPropertiesConfig.getFilePath() + htmlName;
        PrintStream printStream = null;
        try {
            printStream = new PrintStream(new FileOutputStream(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String contentHead = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>泗洪工会</title>\n" +
                "</head>\n" +
                "<body>\n";

        String contentFoot = "</body>\n" +
                "</html>";
        //byte[] asBytes = Base64.getDecoder().decode(htmlContent);
        //System.out.println("内容:" + htmlContent);
        printStream.println(contentHead + htmlContent + contentFoot);
        HashMap<String, String> map = new HashMap<>();
        map.put("filePath", fileName);
        map.put("accessPath", systemPropertiesConfig.getAccessPath() + htmlName);
        return systemPropertiesConfig.getAccessPath() + htmlName;
    }
}
